import Icon from '@/components/Icon'
import { RootState } from '@/types/store'
import { NavBar, Input, List } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import io, { Socket } from 'socket.io-client'
import { getToken } from '@/utils/storage'
type MessageList = { type: 'robot' | 'user'; text: string }[]

const Chat = () => {
  const refList = useRef<HTMLDivElement>(null)
  const ioRef = useRef<Socket | null>(null)
  const history = useHistory()
  const userPhoto = useSelector(
    (state: RootState) => state.profile.profile.photo
  )
  const [value, setValue] = useState('')

  const [messageList, setMessageList] = useState<MessageList>([
    // { type: 'robot', text: '你好呀,我是机器人' },
    // { type: 'user', text: '你好呀，机器人' },
    // { type: 'user', text: '我长的好看吗？' },
    // { type: 'user', text: '你觉得怎么样？' }
  ])

  useEffect(() => {
    // 1. 建立连接
    // 创建客户端实例
    const client = io('http://toutiao.itheima.net', {
      transports: ['websocket'],
      // 在查询字符串参数中传递 token
      query: {
        token: getToken().token
      }
    })

    client.on('connect', () => {
      // 与服务器建立了连接
      setMessageList((messageList) => [...messageList, { type: 'robot', text: '小智同学就绪了' }])
    })

    client.on('message', ({ msg }) => {
      setMessageList((messageList) => [...messageList, { type: 'robot', text: msg }])
    //   setMessageList([...messageList, { type: 'robot', text: msg }])
    })

    ioRef.current = client

    return () => {
      //   2. 断开连接
      ioRef.current?.close()
    }
  }, [])

  useEffect(() => {
    refList.current!.scrollTop = refList.current!.scrollHeight
  }, [messageList])

  const onSendMessage = () => {
    if (value.trim() === '') {
      return
    }

    // 1. 发消息
    ioRef.current?.emit('message', { msg: value, timestamp: Date.now() })
    // 2. 添加到聊天记录
    setMessageList([...messageList, { type: 'user', text: value }])

    // 3. 清空
    setValue('')
  }

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="fixed-header" onBack={() => history.go(-1)}>
        小智同学
      </NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list" ref={refList}>
        {messageList.map((it, idx) => {
          if (it.type === 'robot') {
            return (
              <div key={idx} className="chat-item">
                <Icon type="iconbtn_xiaozhitongxue" />
                <div className="message">{it.text}</div>
              </div>
            )
          } else {
            return (
              <div key={idx} className="chat-item user">
                <img src={userPhoto} alt="" />
                <div className="message">{it.text}</div>
              </div>
            )
          }
        })}
      </div>

      {/* 底部消息输入框 */}
      <div className="input-footer">
        {/* <Input className="no-border" placeholder="请描述您的问题" />
        <Icon type="iconbianji" /> */}
        <List.Item
          className="login-code-extra"
          extra={<span className="code-extra" onClick={onSendMessage}>发送</span>}>
          <Input
            value={value}
            onChange={val => setValue(val) }
          className="no-border" placeholder="请描述您的问题" />
        </List.Item>

        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chat
